using Argar.OpenCV;
using NatCamU.Core;
using NatCamU.Core.UI;
using OpenCVForUnity;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using cvRect = OpenCVForUnity.Rect;

namespace Argar.Camera.Example
{
    [RequireComponent(typeof(AdvancedNatcamToMatHelper))]
    public class PatternMatchExample : MonoBehaviour
    {
        public NatCamPreview preview;
        public int matchFrames = 15;
        public Text textMatch;
        public string detectScene = "TestTool";

        private PatternDetector patternDetector;
        private AdvancedNatcamToMatHelper matHelper;
        private int currentFrames = 0;
        private Mat patternMat;

        public GameObject PattamD;

        public NatCamPreview capturePreview;

        ///// <summary>
        ///// 存放浏览使用的Texture
        ///// </summary>
        private Texture2D patternTexture;
        // Use this for initialization

        //public Image image;
        void Start()
        {
            matHelper = GetComponent<AdvancedNatcamToMatHelper>();
            matHelper.Init();

            Debug.Log("matHelper Init");

            //从路径读取图片
            string savePath = Application.persistentDataPath;

            patternDetector = new PatternDetector();
            Mat patternMat = Imgcodecs.imread(savePath + "/outputImg.jpg");
            Imgproc.cvtColor(patternMat, patternMat, Imgproc.COLOR_BGR2RGB);

            Debug.Log("patterMat: " + patternMat.ToString() + "; Count: " + patternMat.total());

            patternTexture = new Texture2D(patternMat.cols(), patternMat.rows(), TextureFormat.RGBA32, false);
            Utils.matToTexture2D(patternMat, patternTexture);

            capturePreview.Apply(patternTexture);

            patternDetector.buildPatternFromImage(patternMat);
           

            patternMat.Dispose();
            patternMat = null;

            
        }

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                patternDetector.Dispose();
                matHelper.Stop();
                SceneManager.LoadScene(detectScene);
            }
        }

        public void OnMouseEnter()
        {
            patternDetector.Dispose();
            matHelper.Stop();
        }


        public void OnStartCallBack()
        {
            Debug.Log("Init Preview");
            preview.Apply(NatCam.Preview);
        }

        public void OnDisposeCallBack()
        {
            patternMat.Dispose();
            //Texture2D.Destroy(patternTexture);
        }

        public void OnFramCallBack()
        {
            if(NatCam.IsPlaying && matHelper.GetMat() != null)
            {
                if(currentFrames < matchFrames)
                {
                    ++currentFrames;
                    return;
                }

                Mat currentMat = matHelper.GetMat();

                //获取图像中央的正方形作为图案
                int rectWidth = (int)(Mathf.Min(currentMat.width(), currentMat.height()) * 0.6f);
                cvRect patternRect = new cvRect(currentMat.width() / 2 - rectWidth / 2, currentMat.height() / 2 - rectWidth / 2, rectWidth, rectWidth);


                patternMat = patternMat ?? new Mat(currentMat, patternRect);


                bool isMatched = patternDetector.findPattern(patternMat);


                if (isMatched)
                {
                    textMatch.text = "Matched";
                    textMatch.color = Color.green;
                }
                else
                {
                    textMatch.text = "UnMatched";
                    textMatch.color = Color.red;
                }

                currentFrames = 0;
            }
        }
        //private void OnPhoto(Texture2D photo, Orientation orientation)
        //{

        //    Mat imgMat = new Mat(photo.height, photo.width, CvType.CV_8UC3);


        //    patternTexture = new Texture2D(patternMat.cols(), patternMat.rows(), TextureFormat.RGBA32, false);

        //    Utils.matToTexture2D(imgMat, patternTexture);

        //    capturePreview.Apply(patternTexture);
        //    imgMat.Dispose();
        //    imgMat = null;
        //    Texture2D.Destroy(photo);
        //}

        public void Backback()
        {
            PattamD.SetActive(true);
            this.gameObject.SetActive(false);
        }
        public void QuitBut()
        {
            Application.Quit();
        }
    }
}


